package com.zc.demo.xmlparser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by zhangchi9 on 2016/12/12.
 */
public class DomParser implements XmlDocument {
    private Document document;//org.w3c.dom.Document  已被JDK内置
    private String fileName;
    private DocumentBuilder documentBuilder;

    public DomParser() {
        try {
            //创建document生成器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //创建document生成器
            DocumentBuilder builder = factory.newDocumentBuilder();
            this.documentBuilder = builder;
            //创建document对象不赋值
            this.document = builder.newDocument();
            fileName = "D:\\dom.xml";
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String assembleXml() {
        String xml = null;

        //创建一个xml文件根节点
        Element root = document.createElement("employees");
        //把根节点加到xml文档结构下面
        document.appendChild(root);
        //创建employee节点
        Element employee = document.createElement("employee");

        //创建name节点
        Element name = document.createElement("name");
        //创建一个内容,并把内容加到name节点下面
        name.appendChild(document.createTextNode("张驰"));
        //把name加到employee下面
        employee.appendChild(name);

        //同理 创建一个sex和age节点 放到employee
        Element sex = this.document.createElement("sex");
        sex.appendChild(this.document.createTextNode("m"));
        employee.appendChild(sex);

        Element age = this.document.createElement("age");
        age.appendChild(this.document.createTextNode("30"));
        employee.appendChild(age);

        //把employee放到跟节点下
        root.appendChild(employee);

        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            //把DOM写回XML文件
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(document);

            PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
            StreamResult result = new StreamResult(pw);
            transformer.transform(source, result);

            System.out.println("生成XML文件成功!");
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xml;
    }

    @Override
    public void parseXml(String xml) {
        try {
            // 读取xml文件
            Document document = documentBuilder.parse(fileName);
            //获取节点集合
            NodeList employees = document.getChildNodes();

            for (int i = 0; i < employees.getLength(); i++) {
                Node node = employees.item(i);
                NodeList employeeMeta = node.getChildNodes();
                for (int j = 0; j < employeeMeta.getLength(); j++) {
                    System.out.println(employeeMeta.item(j).getNodeName()
                            + ":" + employeeMeta.item(j).getTextContent());
                }
            }
            System.out.println("Xml：解析完毕！");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
